<?php


namespace app\shop\controller\pc;


use app\BaseController;
use app\shop\model\user\MessageModel;
use app\shop\model\user\UserModel;

class ChatController extends BaseController
{
    /**
     * 聊天列表
     * @return \think\response\Json
     */
    public function getContacts()
    {
        try {
            $where = [];
            $userId = $this->request->middleware('userId');
            $where[] = ['chat_status', '=', 1];
            $where[] = ['from_user|to_user', '=', $userId];
            $search = $this->request->param('search', '', 'trim');
            if ($search) {
                $uid = UserModel::where('realname|mobile', 'like', "%{$search}%")->value('user_id');
                $chatIdentify = chat_identify($uid, $userId);
                $where[] = ['chat_identify', '=', $chatIdentify];
            }
            $field = 'msg_id,content as lastContent,is_group,at as is_at,type,chat_identify,from_user,to_user,order_id';
            $list = MessageModel::where($where)
                ->field($field)
                ->order('msg_id', 'desc')
                ->group('chat_identify,order_id')
                ->select();
            foreach ($list as &$value) {
                $unread = MessageModel::where('to_user', $userId)
                    ->where('is_read', 0)
                    ->where('is_group', 0)
                    ->where('chat_status', 1)
                    ->group('from_user,order_id')
                    ->count('msg_id');
                $value['unread'] = $unread;
                $lastSendTime = MessageModel::where('chat_identify', $value['chat_identify'])
                    ->where('order_id', $value['order_id'])
                    ->max('create_time');
                $value['lastSendTime'] = intval($lastSendTime * 1000);

                $friendId = $value['from_user'] == $userId ? $value['to_user'] : $value['from_user'];
                $friendInfo = UserModel::find($friendId);
                $value['user_id'] = $friendInfo['user_id'];
                $value['realname'] = $friendInfo['realname'];
                $value['account'] = $friendInfo['mobile'];
                $value['avatar'] = $friendInfo['avatar'];
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}